#!groovy

def call(String jenkinsLabel,String projectName) {
    echo projectName
    echo jenkinsLabel
    node("${jenkinsLabel}"){
        def KUTUI_GROUP="https://push.xuthus.cc/group"
        def ARTI_IPPORT = '10.21.1.105:8083'
        def DEPLOY_VERSION="SNAPSHOT-1.${BUILD_NUMBER}"
        try {
        def PROJECT_NAME = projectName.toLowerCase()
        def NODE_HOSTNAME='master'

        def HTTP_PORT='18080'
        def DEBUG_PORT='5015'
        def DUBBO_REGISTRY_ADDRESS='10.21.1.104:2181'
        if(env.BRANCH_NAME == "master"){
            HTTP_PORT='18082'
            DEBUG_PORT='15015'
            DUBBO_REGISTRY_ADDRESS='10.21.1.101:2181'
            DEPLOY_VERSION="RELEASE-1.${BUILD_NUMBER}"
        }

        def GIT_URL = 'http://10.20.20.20/cxyjy/ep_201906_005.git'
        ////////////////////////////以下是模板
        def SONAR_SOURCES=projectName
        def POM_PATH=SONAR_SOURCES+'/pom.xml'
        def artiServer = Artifactory.newServer url: 'http://'+ARTI_IPPORT+'/artifactory/', credentialsId: 'artifactory-credential'
        def ARTIFACTORY_API_KEY = 'AKCp5fUsRZTd81jFmUaMRAz6y6CWQ9tp3Vm6MekjThnZKGtQbbW18ZM5TZSZH6judbCoikKPK'
        def ARTIFACTORY_URL = 'http://'+ARTI_IPPORT+'/artifactory/'
        def rtMaven = Artifactory.newMavenBuild()
        def buildInfo = Artifactory.newBuildInfo()
        def RESOLVE_SNAPSHOT_REPO = 'libs-snapshot'
        def RESOLVE_RELEASE_REPO = 'libs-release'
        def DEPLOY_SNAPSHOT_REPO = 'libs-snapshot-local'
        def DEPLOY_RELEASE_REPO = 'libs-release-local'
        def PROMOTION_SOURCE_REPO = 'libs-snapshot-local'
        def PROMOTION_TARGET_REPO = 'libs-release-local'
        def MAVEN_GOALS = 'clean install -DskipTests'
        //sonar
        def SONAR_HOST_URL = 'http://10.21.1.103:9000'
        def SONAR_SERVER = 'sonar'
        def SONAR_SCANNER_TOOL = 'sonar'
        def SONAR_PROJECT_KEY = "${JOB_NAME}".replace("/","_")+"_"+projectName
      //git
        def GIT_CREDENTIALS_ID = 'd844735b-a362-47d5-9b55-f9a7b105fcb2'
        def mavenHome='/root/.m2'
        if(env.BRANCH_NAME == "master"){
            //测试分支才需要deploy
            mavenHome='/root/.m2-test'
        }
        docker.image(ARTI_IPPORT+'/docker-remote/maven:3.3.3').inside("-v /root/.sonarqube/sonar:/sonar -v ${mavenHome}:/root/.m2 -v /var/run/docker.sock:/var/run/docker.sock -v /usr/bin/docker:/usr/bin/docker --user root") {
                withEnv(['MAVEN_HOME=/usr/share/maven/', 'JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64', 'PATH+MAVEN=${env.JAVA_HOME}/bin:${env.MAVEN_HOME}/bin']) {

                    stage('Prepare') {
                        echo "${env.BRANCH_NAME}"
                        echo "环境准备"
                        rtMaven.resolver server: artiServer,
                                         releaseRepo: RESOLVE_RELEASE_REPO,
                                         snapshotRepo: RESOLVE_SNAPSHOT_REPO
                        rtMaven.deployer server: artiServer,
                                         releaseRepo: DEPLOY_RELEASE_REPO,
                                         snapshotRepo: DEPLOY_SNAPSHOT_REPO
                    }

                    stage('SCM') {
                        git url: GIT_URL,
                            branch: env.BRANCH_NAME,
                            changelog: true,
                            credentialsId: GIT_CREDENTIALS_ID
                    }
                    stage('env capture') {
                        echo "收集系统变量"
                        buildInfo.env.capture = true
                    }
                    //Sonar 静态代码扫描
                    stage('Sonar') {
                        try {
                            if (env.BRANCH_NAME == "master") {
                                def scannerHome = tool SONAR_SCANNER_TOOL;
                                withSonarQubeEnv(SONAR_SERVER) {
                                    sh "${scannerHome}/bin/sonar-scanner -Dsonar.language=java -Dsonar.projectKey=${SONAR_PROJECT_KEY} -Dsonar.sources=${SONAR_SOURCES} -Dsonar.host.url=${SONAR_HOST_URL} -Dsonar.java.binaries=*"
                                }
                            }
                        }catch(exception){
                            echo "无法完成静态代码扫描"+exception
                        }
                    }
                    //添加sonar扫描结果到包上
                    stage("Sonar Quality Gate") {
                        try{
                            if (env.BRANCH_NAME == "master") {
                                timeout(time: 1, unit: 'MINUTES') {
                                    sleep 20
                                    // Just in case something goes wrong, pipeline will be killed after a timeout
                                    def qg = waitForQualityGate() // Reuse taskId previously collected by withSonarQubeEnv
                                    if (qg.status != 'OK') {
                                        error "Pipeline aborted due to quality gate failure: ${qg.status}"
                                    } else {
                                        //获取sonar扫描结果
                                        def surl="${SONAR_HOST_URL}/api/measures/component?componentKey=${SONAR_PROJECT_KEY}&metricKeys=alert_status,quality_gate_details,coverage,new_coverage,bugs,new_bugs,reliability_rating,vulnerabilities,new_vulnerabilities,security_rating,sqale_rating,sqale_index,sqale_debt_ratio,new_sqale_debt_ratio,duplicated_lines_density&additionalFields=metrics,periods"
                                        def response=httpRequest consoleLogResponseBody: true, contentType: 'APPLICATION_JSON', ignoreSslErrors: true, url: surl

                                        def propssonar = readJSON text: response.content
                                        if (propssonar.component.measures) {
                                            propssonar.component.measures.each{ measure ->
                                                def val
                                                if (measure.periods){
                                                    val = measure.periods[0].value
                                                }else {
                                                    val = measure.value
                                                }
                                                rtMaven.deployer.addProperty("sonar.quality.${measure.metric}", val)
                                            }
                                        }

                                        //增加sonar扫描结果到artifactory
                                        rtMaven.deployer.addProperty("qulity.gate.sonarUrl", SONAR_HOST_URL + "/dashboard/index/" + SONAR_PROJECT_KEY)
                                    }
                                }
                            }
                        }catch(exception){
                            echo '没有拿到静态代码扫描报告'+exception
                        }
                    }
                    stage('add jiraResult') {
                        if (env.BRANCH_NAME == "master") {
                            echo "add jiraResult"
                            //def requirements = getRequirementsIds();
                            //echo "requirements : ${requirements}"

                            //def revisionIds = getRevisionIds();
                            //echo "revisionIds : ${revisionIds}"
                            //rtMaven.deployer.addProperty("project.issues", requirements).addProperty("project.revisionIds", revisionIds)
                        }
                    }
                    //maven 构建
                    stage('mvn build') {
                        rtMaven.deployer.deployArtifacts = false
                        rtMaven.run pom: POM_PATH, goals: MAVEN_GOALS, buildInfo: buildInfo
                    }
                    stage('package deploy to aitifactory'){
                        if (env.BRANCH_NAME == "master") {
                            rtMaven.deployer.deployArtifacts buildInfo
                            artiServer.publishBuildInfo buildInfo
                        }
                    }
                    //进行测试
                    stage('basic test') {
                        if (env.BRANCH_NAME == "master") {
                            echo "add test step"
                        }
                    }
                    stage('xray scan') {
                        if (env.BRANCH_NAME == "master") {
                            def xrayConfig = [
                                'buildName'  : buildInfo.name,
                                'buildNumber': buildInfo.number,
                                'failBuild'  : false
                            ]
                           // def xrayResults = artiServer.xrayScan xrayConfig
                           // echo xrayResults as String
                       }
                    }
                    //promotion操作，进行包的升级
                    stage('promotion') {
                        if (env.BRANCH_NAME == "master") {
                            def promotionConfig = [
                                    'buildName'          : buildInfo.name,
                                    'buildNumber'        : buildInfo.number,
                                    'targetRepo'         : PROMOTION_TARGET_REPO,
                                    'comment'            : 'this is the promotion comment',
                                    'sourceRepo'         : PROMOTION_SOURCE_REPO,
                                    'status'             : 'Released',
                                    'includeDependencies': false,
                                    'failFast'           : true,
                                    'copy'               : true
                            ]
                            artiServer.promote promotionConfig
                        }
                    }

                    stage('build && push'){
                        sh "cd ${SONAR_SOURCES}/ &&" +
                                "docker login -u admin -p Lzqzhu1241jie ${ARTI_IPPORT} && " +
                                "docker build -f ./Dockerfile -t ${ARTI_IPPORT}/docker-local/${PROJECT_NAME}:${DEPLOY_VERSION} .&&" +
                                "docker push ${ARTI_IPPORT}/docker-local/${PROJECT_NAME}:${DEPLOY_VERSION}"
                    }

                    stage('deploy'){
                            sh '''
                                export SERVICE_IMAGE='''+ARTI_IPPORT+'''/docker-local/''' + "${PROJECT_NAME}" + ''':''' + "${DEPLOY_VERSION}" + '''
                                export DEBUG_PORT=''' + "${DEBUG_PORT}" + '''
                                export HTTP_PORT='''+ "${HTTP_PORT}" + '''
                                export DUBBO_REGISTRY_ADDRESS=''' + "${DUBBO_REGISTRY_ADDRESS}" + '''
                                export NODE_HOSTNAME=''' + "${NODE_HOSTNAME}" + '''
                                docker stack deploy -c ./jenkins/bridge-docker-compose.yml --with-registry-auth ''' + "${PROJECT_NAME}"+'''_'''+"${env.BRANCH_NAME}"+'''
                                    '''
                                //添加元数据
                                def pom = readMavenPom file: '${SONAR_SOURCES}/pom.xml'
                                def latestVersionUrl = "${ARTIFACTORY_URL}api/search/latestVersion?g=${pom.parent.groupId.replace(".","/")}&a=${pom.artifactId}&v=${pom.parent.version}&repos=${PROMOTION_TARGET_REPO}"
                                def latestVersionUrlResponse = httpRequest consoleLogResponseBody: true,
                                                                           customHeaders: [[name: 'X-JFrog-Art-Api',
                                                                           value: ARTIFACTORY_API_KEY]],
                                                                           ignoreSslErrors: true,
                                                                           url: latestVersionUrl
                                def jarLatestVersion = latestVersionUrlResponse.content
                                httpRequest httpMode: 'PUT',
                                            consoleLogResponseBody: true,
                                            customHeaders: [[name: 'X-JFrog-Art-Api', value: ARTIFACTORY_API_KEY]],
                                            url: "${ARTIFACTORY_URL}api/storage/${PROMOTION_TARGET_REPO}/${pom.parent.groupId.replace(".","/")}/${pom.artifactId}/${pom.parent.version}/${pom.artifactId}-${jarLatestVersion}.jar?properties=deploy.tool=dockerswarm;deploy.env=host102"
            
                    }
                }
            }
            withCredentials([string(credentialsId: 'kutui-token', variable: 'KUTUI_KEY')]) {
                echo "完成构建，发qq"
                sh "curl ${KUTUI_GROUP}/${KUTUI_KEY}?c=构建状态:SUCCESS:$projectName:${DEPLOY_VERSION}-${env.BRANCH_NAME}"
            }
        }catch(exception1){
            withCredentials([string(credentialsId: 'kutui-token', variable: 'KUTUI_KEY')]) {
                echo "构建异常，发qq"
                sh "curl ${KUTUI_GROUP}/${KUTUI_KEY}?c=构建状态:FAILED:$projectName:${DEPLOY_VERSION}-${env.BRANCH_NAME}"
            }
            throw exception1
        }
    }
}